<template>
    <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="ruleFormRef">
        <el-form-item label="角色：" prop="user">
            <el-input v-model="formInline.user" placeholder="请输入用户名" />
        </el-form-item>
        <div class="block">
            <el-form-item prop="region">
                <span class="demonstration">创建时间：</span>
                <el-date-picker v-model="formInline.region" type="daterange" range-separator="～"
                    start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
            </el-form-item>
        </div>
        <el-form-item>
            <el-button type="primary" @click="search()">搜索</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
    <div class="botton-group">
        <el-button type="primary" plain @click="firstadd()">新增</el-button>
        <el-button plain @click="delect()">删除</el-button>
        <el-button plain>更多操作</el-button>
    </div>
    <el-table ref="multipleTableRef" :data="state.roleData" width="100%" height="460"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="角色">
            <template #default="scope">{{ scope.row.roleName }}</template>
        </el-table-column>
        <el-table-column property="remark" label="描述">
            <template #default="scope">{{scope.row.remark==null?'未填写': scope.row.remark}}</template>
        </el-table-column>
        <el-table-column property="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column property="modifyTime" label="修改时间" show-overflow-tooltip>
            <template #default="scope">{{scope.row.modifyTime==null?'从未修改': scope.row.modifyTime}}</template>
        </el-table-column>
        <el-table-column label="操作" show-overflow-tooltip>
            <template #default="scope">
                <el-button @click="changeOne(scope.$index, scope.row)" :icon="Tools" circle />
                <el-button :icon="View" circle />
            </template>
        </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
        <el-pagination v-model:currentPage="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 20, 30, 40]"
            :small="small" :disabled="disabled" :background="background" :total="state.page"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-model="dialogFormVisible" :title="state.addchange">
        <el-form :model="form">
            <el-form-item label="角色名称" :label-width="formLabelWidth">
                <el-input v-model="form.userName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth">
                <el-input v-model="form.remark" type="textarea" autocomplete="off" />
            </el-form-item>
            <div class="account-list">
                <div>
                    <p style="margin: 10px 10px;">权限选择：</p>
                    <el-tree :data="state.menuData" :props="defaultProps" show-checkbox ref="treeRef" node-key="key"
                        style="overflow-y: auto;height: 210px;">
                    </el-tree>
                </div>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addSome()">确认</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" title="删除确认" width="30%">
        <span>你确定要删除以下用户吗？
            <p style="margin-top: 10px;">{{state.delname.toString()}}</p>
        </span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="realDel()">确定</el-button>
            </span>
        </template>
    </el-dialog>

</template>

<script setup lang="ts">
import { getAllRoleApi, delByIdApi, getOneRole, addRoleApi, changeOneRole } from '../../apis/role'
import { getMenuApi } from '../../apis/menu'
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElTable, ElTree } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
    Tools,
    View,
} from '@element-plus/icons-vue'

interface User {
    [x: string]: any;
    date: string
    name: string
    address: string
}
interface Tree {
    [x: string]: any;
    label: string
    children?: Tree[]
}

const handleNodeClick = (data: Tree) => {
    console.log(data)
}

const ruleFormRef = ref<FormInstance>()
const formInline = reactive({
    user: '',
    region: '',
})
const state = reactive({
    roleData: [],
    page: 0,
    menuData: [] as any,
    checkData: [] as any,
    delId: "",
    delname: "",
    addchange: "",
    pageSize: 10,
    pageNum: 1
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const dialogVisible = ref(false)
const formLabelWidth = '80px'
const form = reactive({
    name: '',
    region: '',
    date1: '',
    date2: '',
    delivery: false,
    type: [],
    resource: '',
    desc: '',
    userName: '',
    remark: '',
    roleId: ''
})
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
    state.pageSize = val
    console.log(`${val} items per page`)
    getAllRole(`pageSize=${val}`)
}
const handleCurrentChange = (val: number) => {
    state.pageNum = val
    console.log(`current page: ${val}`)
    getAllRole(`pageNum=${val}`)
}

const defaultProps = {
    children: state.menuData.children,
    label: "title",
}

const getCheckedKeys = () => {
    console.log(treeRef.value!.getCheckedKeys(false))
    state.checkData = treeRef.value!.getCheckedKeys(false)
}

const setCheckedKeys = (data: any) => {
    treeRef.value!.setCheckedKeys(data, false)
}

const resetChecked = () => {
    treeRef.value!.setCheckedKeys([], false)
}

const resetForm = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return;
    ruleForm.resetFields();
    getAllRole()
};

function search() {
    console.log(formInline.region[0]);
    const a = `roleName=${formInline.user}&createTimeFrom=${formInline.region[0]}&createTimeTo=${formInline.region[1]}&`
    getAllRole(a)
    console.log(typeof formInline.user);


}

function delect() {
    const data = JSON.parse(JSON.stringify(multipleSelection.value));
    console.log(data);
    const a = data.map((item: {
        [x: string]: any; userId: any
    }) => {
        return item.roleId
    })
    state.delId = a
    const b = data.map((item: {
        [x: string]: any; username: any
    }) => {
        return item.roleName
    })
    state.delname = b
    console.log(a);
    console.log(b);
    if (data != "") {
        dialogVisible.value = true
    } else {
        ElMessage.error("没有选中任何用户，无法删除")
    }


}

function realDel() {
    // delSome(state.delname)
    dialogVisible.value = false
    delOne()

}

async function getAllRole(data?: any) {
    const res = await getAllRoleApi(data);
    console.log(res);
    state.roleData = res.rows
    state.page = res.total


}

async function getMenu(data?: any) {
    const res = await getMenuApi(data)
    console.log(res);
    state.menuData = res.rows.children

}

function changeOne(index: number, row: User) {
    state.addchange = "修改用户"
    console.log(row);
    getMenuByRoleId(row.roleId)
    form.userName = row.roleName
    form.remark = row.remark
    form.roleId = row.roleId
    dialogFormVisible.value = true

}

function addSome() {
    dialogFormVisible.value = false
    console.log(state.checkData);
    getCheckedKeys()
    // console.log(String(state.checkData));
    console.log(state.addchange);

    if (state.addchange == "新增用户") {
        addRole()
    } else {
        realChange()
    }

}
function firstadd() {
    state.addchange = "新增用户"
    dialogFormVisible.value = true
    resetChecked()
}
async function addRole() {
    const a = `roleName=${form.userName}&remark=${form.remark}&menuId=${String(state.checkData)}`
    const res = await addRoleApi(a)
    console.log(res);
    if (res == "") {
        ElMessage.success("角色添加成功")
        getAllRole(`pageSize=${state.pageSize}&pageNum=${state.pageNum}`)
    }
}

async function delOne() {
    const res = await delByIdApi(state.delId)
    console.log(res);
    if (res == "") {
        ElMessage.success("角色删除成功")
        getAllRole(`pageSize=${state.pageSize}&pageNum=${state.pageNum}`)
    }
}

async function getMenuByRoleId(data: any) {
    const res = await getOneRole(data)
    console.log(res);
    setCheckedKeys(res)

}
async function changeOneByRole(data: any) {
    const res = await changeOneRole(data)
    console.log(res);
    if (res == "") {
        ElMessage.success("角色修改成功")
        getAllRole(`pageSize=${state.pageSize}&pageNum=${state.pageNum}`)
    }
}
function realChange() {
    const a = `roleName=${form.userName}&remark=${form.remark}&roleId=${form.roleId}&menuId=${String(state.checkData)}`

    changeOneByRole(a)
}
onMounted(() => {
    getAllRole()
    getMenu()
})
</script>

<style scoped>
.demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
}

.demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    flex: 1;
}

.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

.block {
    width: 40%;
}

.demo-form-inline {
    display: flex;
}

.demonstration {
    color: #606266;
    font-size: 14px;
}

.botton-group {
    margin-top: 5px;
    margin-bottom: 20px;
}

.demo-pagination-block {
    margin-top: 20px;
}
</style>